<template>
  <BoTable
    :columns="columns"
    :request="getPowerSupplyList"
    ref="tableRef"
    :row-selection="rowSelection"
    row-key="id"
    :show-index="true"
  >
    <template #toolbars>
      <Space :size="8">
        <Button type="primary" @click="onAdd"> 新增 </Button>
        <Button
          type="primary"
          :disabled="!selectKeys.length"
          @click="onDelete(null)"
        >
          删除
        </Button>
      </Space>
    </template>
  </BoTable>
  <FormModal :columns="items">
    <template #showTable="{ model }">
      <FormItemRest>
        <BoTable
          :columns="columnsAdd"
          :request="
            (params) =>
              _powerSupplyDeviceList({
                ...params,
                host: model.host,
                username: model.username,
                password: model.password,
              })
          "
          ref="tableAddRef"
          :row-selection="rowAddSelection"
          row-key="id"
          height="auto"
          :autoload="false"
          :show-index="{ fixed: true }"
        ></BoTable>
      </FormItemRest>
    </template>
  </FormModal>
  <!-- 查看关联设备 -->
  <FormModal2 :columns="itemsRelatedDevice">
    <template #showTable>
      <RelatedDevice :powerId="powerId"></RelatedDevice>
    </template>
  </FormModal2>
</template>

<script setup lang="tsx">
import { computed, onMounted, ref } from 'vue';
import { getDeviceManufacturerSelect } from '@/api';
import { useFormModal } from '@boeyo/hooks';
import { listToEnum, listToOption } from '@boeyo/shared';
import { BoFormProps, BoTable, BoTableProps } from '@boeyo/ui';
import { Button, FormItemRest, Modal, Space, message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import {
  addPowerSupply,
  deletePowerSupply,
  getPowerSupplyList,
  modelOption,
  powerSupplyDeviceList,
} from './api';
import RelatedDevice from './components/RelatedDevice.vue';
import { deviceEnum } from './constants';

const router = useRouter();

const tableRef = ref();
const selectKeys = ref<any[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    onChange(values, all) {
      selectKeys.value = values;
    },
  };
});

// 获取表单下拉框数据
const mnufacturerOptions = ref<any[]>([]);
const manufacturerEnum = ref<Record<string, any>>({});

const init = () => {
  getDeviceManufacturerSelect(deviceEnum.POWER).then(({ data }) => {
    mnufacturerOptions.value = listToOption(data, 'name', 'facId');
    manufacturerEnum.value = listToEnum(data, 'name', 'facId');
  });
};
init();

const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '电源设备ID',
    dataIndex: 'powerSupplyId',
    hideInSearch: true,
  },
  {
    title: '电源设备编号',
    dataIndex: 'powerSupplyCode',
  },
  {
    title: '电源设备名称',
    dataIndex: 'powerSupplyName',
  },
  {
    title: '电源设备厂商',
    dataIndex: 'manufacturer',
    hideInSearch: true,
    ellipsis: true,
  },
  {
    title: '电源设备厂商',
    dataIndex: 'facId',
    valueEnum: manufacturerEnum.value,
    valueType: 'select',
    hideInTable: true,
  },
  {
    title: '硬件版本',
    dataIndex: 'hardwareVersion',
    hideInSearch: true,
  },
  {
    title: '软件版本',
    dataIndex: 'version',
    hideInSearch: true,
  },
  {
    title: '经度',
    dataIndex: 'longitude',
    hideInSearch: true,
  },
  {
    title: '纬度',
    dataIndex: 'latitude',
    hideInSearch: true,
  },
  {
    title: '地址',
    dataIndex: 'address',
    hideInSearch: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    hideInSearch: true,
  },
  {
    title: '创建人',
    dataIndex: 'createBy',
    hideInSearch: true,
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    hideInSearch: true,
  },
  {
    title: '更新人',
    dataIndex: 'updateBy',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    actions: [
      {
        text: '关联设备',
        onClick(record) {
          onViewDevice(record);
        },
      },
      {
        text: '远程控制',
        onClick(record) {
          onRemoteControl(record);
        },
      },
      {
        text: '删除',
        onClick(record) {
          onDelete(record);
        },
      },
    ],
  },
]);

const tableAddRef = ref();
const selectAddKeys = ref<any[]>([]);
const selectAddRows = ref<any[]>([]);
const rowAddSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    onChange(values, all) {
      selectAddKeys.value = values;
      selectAddRows.value = all;
    },
  };
});
const columnsAdd = computed<BoTableProps['columns']>(() => [
  {
    title: '电源设备ID',
    dataIndex: 'id',
    hideInSearch: true,
    fixed: 'left',
  },
  {
    title: '电源设备编号',
    dataIndex: 'code',
    hideInSearch: true,
  },
  {
    title: '电源设备名称',
    dataIndex: 'name',
  },
  {
    title: '电源设备Id',
    dataIndex: 'powerSupplyId',
    hideInSearch: true,
    hideInTable: true,
  },
  {
    title: '经度',
    dataIndex: 'longitude',
    hideInSearch: true,
  },
  {
    title: '纬度',
    dataIndex: 'latitude',
    hideInSearch: true,
  },
  {
    title: '硬件版本',
    dataIndex: 'hardwareVersion',
    hideInSearch: true,
  },
  {
    title: '软件版本',
    dataIndex: 'version',
    hideInSearch: true,
  },
]);

const modelOptions = ref([]);
const updateModels = async (facId: number) => {
  const res = await modelOption({ facId, type: '2' });
  modelOptions.value = listToOption(res.data, 'model', 'modelId');
};

// 新增表单
const items = computed<BoFormProps['columns']>(() => [
  {
    title: '设备厂商',
    dataIndex: 'facId',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择厂商',
          trigger: 'blur',
        },
      ],
    },
    fieldProps(state) {
      return {
        placeholder: '请选择厂商',
        options: mnufacturerOptions.value,
        onChange(value) {
          state.modelId = undefined;
          updateModels(value as number);
        },
      };
    },
  },
  {
    title: '型号',
    dataIndex: 'modelId',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择型号版本',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请选择型号版本',
      options: modelOptions.value,
    },
  },
  {
    title: 'host',
    dataIndex: 'host',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入主机地址',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入主机地址',
    },
  },
  {
    title: '用户名',
    dataIndex: 'username',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入用户名',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入用户名',
    },
  },
  {
    title: '密码',
    dataIndex: 'password',
    valueType: 'password',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入密码',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入密码',
    },
  },
  {
    title: '',
    dataIndex: 'line',
    valueType: 'input',
    colProps: {
      span: 24,
    },
    formItemProps: {
      wrapperCol: {
        span: 24,
      },
      labelCol: {
        span: 2,
      },
    },
    formItemRender() {
      return (
        <div class='border-b-1 mb-5 h-[1px] w-full border-solid border-b-[#fff]'></div>
      );
    },
  },
  {
    title: '',
    dataIndex: 'showTable',
    valueType: 'input',
    colProps: {
      span: 24,
    },
    formItemProps: {
      wrapperCol: {
        span: 24,
      },
      labelCol: {
        span: 2,
      },
    },
  },
]);

const { FormModal, open } = useFormModal({
  size: 'middle',
  column: 2,
});

const onAdd = () => {
  open({
    title: '新增',
    request: async (params: any) => {
      params.list = selectAddRows.value;
      if (params.list.length === 0) {
        message.info('请选择关联设备');
        throw new Error('请选择关联设备');
      }
      await addPowerSupply(params);
      tableRef.value.refresh();
    },
    defaultValue: {
      status: '0',
    },
  });
};

const onDelete = (record?: any) => {
  const ids = record ? record.id : selectKeys.value.join('');

  Modal.confirm({
    title: '删除',
    content: '确定删除当前选中项数据吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      await deletePowerSupply(ids);
      message.success('操作成功');
      tableRef.value.refresh();
    },
  });
};

// 添加调用列表
const _powerSupplyDeviceList = async (params) => {
  if (!params.host || !params.username || !params.password) {
    message.info('请输入ip，用户名和密码');

    return {
      rows: [],
      total: 0,
    };
  }

  params.inline = '1';
  return await powerSupplyDeviceList(params);
};

const onRemoteControl = async (record) => {
  console.log(record.powerSupplyId, 'record.powerSupplyId');

  // const res: any = await getPowerSupplyDetail(record.powerSupplyId);
  // console.log(res.data, 'res');

  router.push({
    name: 'power-remote-control',
    state: {
      // ...res.data,
      powerSupplyId: record.powerSupplyId,
    },
  });
};

// 查看关联设备列表
const itemsRelatedDevice = computed<BoFormProps['columns']>(() => [
  {
    title: '',
    dataIndex: 'showTable',
    valueType: 'input',
    colProps: {
      span: 24,
    },
    formItemProps: {
      wrapperCol: {
        span: 24,
      },
      labelCol: {
        span: 0,
      },
    },
  },
]);

const { FormModal: FormModal2, open: open2 } = useFormModal({
  size: 'middle',
  column: 1,
});

const powerId = ref();
const onViewDevice = (record) => {
  powerId.value = record.id;
  open2({
    title: '查看关联设备',
    request: async (params: any) => {},
    defaultValue: {},
  });
};
</script>
<route lang="json">
{
  "name": "power",
  "meta": { "title": "智能电源管理" }
}
</route>
